<?php

namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ComeBack extends Base
{
    protected $table = 'ddyy_come_back_config';//活动配置表
    protected $siginTable = 'ddyy_activity_sigin_config';//签到配置表
    protected $dayTaskTable = 'ddyy_day_task_config';//语音活动每日任务
    protected $userSiginLog = 'ddyy_user_sign_log';//签到记录表
    protected $mission_stream= 'ddyy_mission_stream_log';//任务流水记录
    protected $jdStream = 'finance_jd_stream';//获取金豆流水
    protected $userTable = 'user';//用户表
    protected $financeRechargeOrder = 'finance_recharge_order';//充值表
    
    protected $comeBackRedisKey = 'COME:BACK:CONFIG';//缓存配置值 COME:BACK:CONFIG {string}=>{json}
    protected $siginListRedis = 'COME:BACK:SIGIN:LIST';//签到配置项缓存 COME:BACK:SIGIN:LIST {string}=>{json}
    protected $dayMissionRedis = 'COME:BACK:MISSION:DAY';//每日任务列表 COME:BACK:MISSION:DAY {string}=>{json}
    protected $allMissionRedis = 'COME:BACK:MISSION:ALL'; //累计任务列表 COME:BACK:MISSION:ALL {string}=>{json}
    protected $missionInfoRedis = 'COME:BACK:MISSION:INFO:';//任务单个详情 COME:BACK:MISSION:INFO:{id} => {json}

    protected $error_log = 'error_comeBack';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //新增配置
    public function addComeBackConfig($data){
        $res = DB::table($this->table)->insert($data);
        Redis::DEL($this->comeBackRedisKey);
        return $res;
    }

    //编辑配置
    public function editComeBackConfig($id, $data){
        $res = DB::table($this->table)->where('id',$id)->update($data);
        Redis::DEL($this->comeBackRedisKey);
        return $res;
    }

    //新增签到配置
    public function insertSiginCongfig($data){
        $res = DB::table($this->siginTable)->insert($data);
        Redis::DEL($this->siginListRedis);
        return $res;
    }

    //编辑签到配置
    public function editSiginCongfig($id, $data){
        $res = DB::table($this->siginTable)->where('sigin_id',$id)->update($data);
        Redis::DEL($this->siginListRedis);
        return $res;
    }

    //新增每日任务
    public function addTask($data){
        $res = DB::table($this->dayTaskTable)->insert($data);
        Redis::DEL($this->dayMissionRedis);
        Redis::DEL($this->allMissionRedis);
        Redis::DEL($this->missionInfoRedis.'*');
        return $res;
    }

    //编辑每日任务
    public function editTask($id,$data){
        $res = DB::table($this->dayTaskTable)->where('task_id',$id)->update($data);
        Redis::DEL($this->dayMissionRedis);
        Redis::DEL($this->allMissionRedis);
        Redis::DEL($this->missionInfoRedis.'*');
        return $res;
    }

    //查看配置项
    public function getComeBackConfig(){
        $data = Redis::get($this->comeBackRedisKey);
        if(empty($data)){
            $data = DB::table($this->table)->where('is_delete',0)->first();
            $data = self::objToArray($data);
            Redis::SET($this->comeBackRedisKey,json_encode($data));
            Redis::EXPIRE($this->comeBackRedisKey,2*86400);
        }else{
            $data = json_decode($data,true);
        }
        return $data; 
    }

    //获取用户手机号
    public function getUserPhone($userId){
        $data = DB::table($this->userTable)->where('user_id',$userId)->first(['mobile_phone']);
        $data = self::objToArray($data);
        return $data;
    }

    //查看用户是否签到了
    public function checkUserSigin($userId,$siginDay){
        $checkInfo = DB::table($this->userSiginLog)->where('user_id',$userId)->where('sign_day',$siginDay)->orderBy('created_at','asc')->first();
        $checkInfo = self::objToArray($checkInfo);
        return $checkInfo;
    }

    //获取签到配置列表
    public function getSiginList($actId){
        $data = Redis::get($this->siginListRedis);
        if(empty($data)){
            $data = DB::table($this->siginTable)->where('act_id',$actId)->where('is_delete',0)->get();
            $data = self::objToArray($data);
            Redis::set($this->siginListRedis,json_encode($data));
            Redis::EXPIRE($this->siginListRedis,2*86400);
        }else{
            $data = json_decode($data,true);
        }
        return $data;
    }

    //获取今日是否签到
    public function chekTodaySigin($userId){
        $startDay = Carbon::today()->startOfDay()->toDateTimeString();
        $endDay = Carbon::today()->endOfDay()->toDateTimeString();
        $checkInfo = DB::table($this->userSiginLog)->where('user_id',$userId)->where('last_time','>=',$startDay)->where('last_time','<=',$endDay)->first();
        $checkInfo = self::objToArray($checkInfo);
        if(!empty($checkInfo)){
            return 1;
        }
        return 0;
    }

    //进行签到
    public function doSigin($userId,$siginInfo){
        try{
            DB::beginTransaction();
            $data = [
                'user_id' => $userId,
                'sign_day' => $siginInfo['day'],
                'sign_id' => $siginInfo['sigin_id'],
                'last_time' => Carbon::now()->toDateTimeString(),
                'created_at' => Carbon::now()->toDateTimeString(),
            ];
            $res = DB::table($this->userSiginLog)->insertGetId($data);
            DB::commit();
            return $res;
        }catch(\Exception $e){
            DB::rollBack();
            write_log($this->error_log,'ERROR 签到失败',['data'=>$data,'line'=>$e->getLine(),'msg'=>$e->getMessage()]);
            return false;
        }  
    }

    //获取单个签到信息
    public function getSiginInfo($siginId, $actId){
        $info = DB::table($this->siginTable)->where('sigin_id',$siginId)->where('act_id',$actId)->first();
        $info = self::objToArray($info);
        return $info;
    }

    //获取活动对应下的每日任务列表
    public function dayMission($actId){
        $data = Redis::get($this->dayMissionRedis);
        if(empty($data)){
            $data = DB::table($this->dayTaskTable)->where('act_id',$actId)->where('is_day',1)->where('type','!=',4)->get();
            $data = self::objToArray($data);
            Redis::SET($this->dayMissionRedis,json_encode($data));
            Redis::EXPIRE($this->dayMissionRedis,2*86400);
        }else{
            $data = json_decode($data,true);
        }
        return $data;
    }

    //获取活动对应下的每日任务列表
    public function mission($actId){
        $data = Redis::get($this->allMissionRedis);
        if(empty($data)){
            $data = DB::table($this->dayTaskTable)->where('act_id',$actId)->where('is_day',0)->where('type','!=',4)->get();
            $data = self::objToArray($data);
            Redis::SET($this->allMissionRedis,json_encode($data));
            Redis::EXPIRE($this->allMissionRedis,2*86400);
        }else{
            $data = json_decode($data,true);
        }
        return $data;
    }

    //查看用户是否完成任务
    public function checkUserMission($userId, $taskId, $is_day){
        $where = function($q)use($userId, $taskId, $is_day) {
            $q->where('user_id',$userId);
            $q->where('task_id',$taskId);
            if($is_day){
                $startTime = Carbon::today()->startOfDay()->toDateTimeString();
                $endTime = Carbon::today()->endOfDay()->toDateTimeString();
                $q->where('created_at','>=',$startTime);
                $q->where('created_at','<=',$endTime);
            }
        };
        $data = DB::table($this->mission_stream)->where($where)->first();
        $data = self::objToArray($data);
        return $data;
    }

    //获取任务详情
    public function getMissionInfo($taskId){
        $data = Redis::get($this->missionInfoRedis.$taskId);
        if(empty($data)){
            $data = DB::table($this->dayTaskTable)->where('task_id',$taskId)->where('is_delete',0)->first();
            $data = self::objToArray($data);
            Redis::SET($this->missionInfoRedis.$taskId,json_encode($data));
            Redis::EXPIRE($this->missionInfoRedis.$taskId,2*86400);
        }else{
            $data = json_decode($data,true);
        }
        return $data;
    }

    //更新任务记录表
    public function updateStreamLog($streamId,$update){
        try{
            DB::beginTransaction();
            DB::table($this->mission_stream)->where('stream_id',$streamId)->update($update);
            DB::commit();
            return true;
        }catch(\Exception $e){
            DB::rollBack();
            write_log($this->error_log,'ERROR 更新任务表',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'data'=>$update]);
            return false;
        }
    }

    //获取对应活动下指定任务类型的任务信息
    public function getMissionInfoByActId($actId, $type, $is_day){
        $data = DB::table($this->dayTaskTable)->where(['act_id'=>$actId,'type'=>$type,'is_delete'=>0,'is_day'=>$is_day])->first();
        $data = self::objToArray($data);
        return $data;
    }

    //新增任务完成信息
    public function insertStream($data){
        try{
            DB::beginTransaction();
            DB::table($this->mission_stream)->insert($data);
            DB::commit();
            return true;
        }catch(\Exception $e){
            DB::rollBack();
            write_log($this->error_log,'ERROR 新增任务流水失败',['data'=>$data,'msg'=>$e->getMessage()]);
            return false;
        }
    }

    //获取用户消耗金豆数
    public function getUserCostJd($userId, $startTime, $endTime){
        $data = DB::table($this->jdStream)->where('user_id',$userId)->where('created_at','>=',$startTime)->where('created_at','<=',$endTime)->where('change_value','<',0)->sum('change_value');
        return abs($data);
    }

    //获取用户充值钻石数
    public function getUserPayDiamond($userId, $startTime, $endTime){
        $data = DB::table($this->financeRechargeOrder)->where('user_id',$userId)->where('status',1)->where('create_timestamp','>=',$startTime)->where('create_timestamp','<=',$endTime)->sum('diamond_amount');
        return $data;
    }
}